package com.huazai.juc.cec.thread.august.fifteen;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Seon
 * @date 2022/8/15 22:57
 */
@Slf4j
public class ThreadLoopPrint {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(5, 1);
        new Thread(() -> {
            waitNotify.print("a", 1, 2);
        }).start();
        new Thread(() -> {
            waitNotify.print("b", 2, 3);
        }).start();
        new Thread(() -> {
            waitNotify.print("c", 3, 1);
        }).start();
    }
}

class WaitNotify {
    private int loopNumber;
    private int flag;

    public WaitNotify(int loopNumber, int flag) {
        this.loopNumber = loopNumber;
        this.flag = flag;
    }

    public void print(String str, int currentFlag, int nextFlag) {
        for (int i = 0; i < loopNumber; i ++) {
            synchronized (this) {
                while (currentFlag != flag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
